package com.xframe.event.bus.core.msg;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;


/**
 * 功能描述:消息接收者
 *
 * @author xufeng
 * @version 1.0
 * 2022-09-26
 */
public class DefReceiveMsg implements IReceiveMsg {

    protected Connection msgConn;
    protected Channel curChannel = null;
    protected String[] queueNames;

    protected int qos = 1;
    protected boolean autoAck = true;
    protected IMsgProc msgProc = null;

    public Channel getCurChannel(){
        return this.curChannel;
    }


    public IMsgProc getMsgProc(){
        return msgProc;
    }

    public Connection getMsgConn() {
        return msgConn;
    }

    public String[] getQueueNames() {
        return queueNames;
    }

//    public String getExchangeName() {
//        return exchangeName;
//    }
//
//    public String getRoutingKey() {
//        return routingKey;
//    }

    public int getQos() {
        return qos;
    }

    public boolean isAutoAck() {
        return autoAck;
    }

    public DefReceiveMsg(Connection msgConn, IMsgProc msgProc, String queueName){
        this.msgConn = msgConn;
        this.msgProc = msgProc;
        this.queueNames = queueName.split(",");
    }

    public DefReceiveMsg(Connection msgConn,IMsgProc msgProc,String queueName,int qos,boolean autoAck){
        this.msgConn = msgConn;
        this.msgProc = msgProc;
        this.queueNames = queueName.split(",");
        this.qos = qos;
        this.autoAck = autoAck;
    }

    public void init(){
        try {
            curChannel = msgConn.createChannel();
            DefaultConsumer defaultConsumer = new DefaultReceiveConsumer(this);
            for (int i = 0; i < this.queueNames.length; i++) {
                String queueName = this.queueNames[i];
                curChannel.queueDeclare(queueName, true, false, false, null);
                curChannel.basicQos(this.qos);
                curChannel.basicConsume(queueName, this.autoAck, defaultConsumer);
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }


}
